<template>
  <div>
    <x-header :left-options="{backText: ''}" @on-click-more="showMenus = true" >选择人群</x-header>
    <div class="ui-body">
      <group title="已选择" v-if="$store.state.SelectedShowEmployeeNames.length">
        <div class="ui-choose-list">
          <div v-for="(item, index) in $store.state.SelectedShowEmployeeNames">
              <div v-html="item"></div>
            <img src="../assets/images/inp_icon.png" style="width: 15px;position: absolute;top: 15px;right: 10px;cursor: pointer;" @click="deleteThis(index)">
          </div>
        </div>
      </group>
      <div>
        
      </div>
      <group title="全部">
        <example :itemA="commonList"></example>
      </group>
      <box gap="10px 20px">
        <x-button  type="primary" link="BACK" style="margin-top: 20px;">确定</x-button>
      </box>
    </div>
  </div>
</template>

<script>
import { Group, Cell, XHeader, Checklist, XButton, Box, CheckIcon } from 'vux'
import Vue from 'vue'
import store from '@/store'
import axios from 'axios'
require('es6-promise').polyfill()
var qs = require('qs')
Vue.component('example', {
  name: 'example',
  components: {
    Group,
    Cell,
    XHeader,
    Checklist,
    XButton,
    Box,
    CheckIcon
  },
  template: `<div>
              <div v-for="(item, index) in itemA" @click.native="changeAll" style="margin-left: 10px">
                <cell :title="item.OrgName" is-link :border-intent="false" :arrow-direction="item.showC ? 'up' : 'down'" @click.native="showChild(item)">
                  <check-icon :value="$store.state.SelectedEmployeeIds.indexOf(item.OrgID) !== -1 ? true : false"  @click.stop.native="selectAll(item.OrgName, item.OrgID, true, item)"></check-icon>
                </cell>
                <example :itemA="item.ChildListOrgMail" v-if="item.ChildListOrgMail.length && item.showC"></example>
                <cell :title="child.value"  v-for="child in item.ListMail" v-if="item.ListMail.length && item.showC" style="margin-right: 13px;margin-left: 10px">
                  <check-icon :value="$store.state.SelectedEmployeeIds.indexOf(child.key) !== -1 ? true : false"  @click.stop.native="selectAll(child.value, child.key, false, item)"></check-icon>
                </cell>
              </div>
            </div>`,
  props: ['itemA', 'SelectedEmployeeIds', 'SelectedEmployeeNames'],
  methods: {
    changeAll () {
      let itemA = this.itemA
      this.itemA = []
      this.itemA = itemA
    },
    selectAll (name, key, flag, item) {
      this.dataInit(key, flag, item)
    },
    dataInit (key, flag, item) {
      let childItem = (item) => {
        if (this.$store.state.SelectedEmployeeIds.indexOf(key) === -1 && flag && item.OrgID) { // 沒有新加的 部門
          let SelectedEmployeeIds = [...new Set([...this.$store.state.SelectedEmployeeIds, ...addAllChild(item)])]
          this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
          checkAllSelect(flag, this.$store.state.commonList[0], key)
        } else if (this.$store.state.SelectedEmployeeIds.indexOf(key) === -1 && !flag) { // 沒有新加的 成員
          let SelectedEmployeeIds = [...this.$store.state.SelectedEmployeeIds, key]
          this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
          checkAllSelect(flag, this.$store.state.commonList[0], key)
        } else if (this.$store.state.SelectedEmployeeIds.indexOf(key) !== -1 && !flag) { // 之前有 要減的 成員
          let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
          SelectedEmployeeIds.splice(SelectedEmployeeIds.indexOf(key), 1)
          this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
          isAllChildSelect(flag, this.$store.state.commonList, key)
        } else if (this.$store.state.SelectedEmployeeIds.indexOf(key) !== -1 && item.OrgID === key && flag) { // 之前有 要減的 部門
          deleteAllChild(item)
          isAllChildSelect(flag, this.$store.state.commonList, key)
        }
        setTimeout(() => {
          let [SelectedShowEmployeeIds, SelectedShowEmployeeNames] = changeSelectNameObj(this.$store.state.commonList, [], [])
          console.log(SelectedShowEmployeeNames)
          this.$store.commit('updateState', {key: 'SelectedShowEmployeeNames', value: SelectedShowEmployeeNames})
          this.$store.commit('updateState', {key: 'SelectedShowEmployeeIds', value: SelectedShowEmployeeIds})
        }, 1)
      }
      // 显示的，名字整理
      let changeSelectNameObj = (item, SelectedShowEmployeeNames, SelectedShowEmployeeIds) => {
        for (let index in item) {
          if (this.$store.state.SelectedEmployeeIds.indexOf(item[index].OrgID) !== -1) {
            SelectedShowEmployeeNames.push(item[index].OrgName)
            SelectedShowEmployeeIds.push(item[index].OrgID)
          } else {
            for (let i in item[index].ListMail) {
              if (this.$store.state.SelectedEmployeeIds.indexOf(item[index].ListMail[i].key) !== -1) {
                SelectedShowEmployeeNames.push(item[index].ListMail[i].value)
                SelectedShowEmployeeIds.push(item[index].ListMail[i].key)
              }
            }
            if (item[index].ChildListOrgMail.length) {
              changeSelectNameObj(item[index].ChildListOrgMail, SelectedShowEmployeeNames, SelectedShowEmployeeIds)
            }
          }
        }
        return [SelectedShowEmployeeIds, SelectedShowEmployeeNames]
      }
      let checkAllSelect = (flag, item, key) => {
        if (flag) {
          if (item.OrgID !== key) {
            for (let index in item.ChildListOrgMail) {
              checkAllSelect(flag, item.ChildListOrgMail[index], key)
            }
          }
          for (let index in item.ChildListOrgMail) {
            if (this.$store.state.SelectedEmployeeIds.indexOf(item.ChildListOrgMail[index].OrgID) === -1) {
              return false
            }
          }
          for (let index in item.ListMail) {
            if (this.$store.state.SelectedEmployeeIds.indexOf(item.ListMail[index].key) === -1) {
              return false
            }
          }
          let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
          SelectedEmployeeIds = [...new Set([...SelectedEmployeeIds, item.OrgID])]
          this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
        } else {
          for (let i in item.ChildListOrgMail) {
            checkAllSelect(flag, item.ChildListOrgMail[i], key)
          }
          if (item.ChildListOrgMail.length === 0 && item.ListMail.length === 0) {
            return false
          }
          for (let index in item.ChildListOrgMail) {
            if (this.$store.state.SelectedEmployeeIds.indexOf(item.ChildListOrgMail[index].OrgID) === -1) {
              return false
            }
          }
          for (let index in item.ListMail) {
            if (this.$store.state.SelectedEmployeeIds.indexOf(item.ListMail[index].key) === -1) {
              return false
            }
          }
          let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
          SelectedEmployeeIds = [...new Set([...SelectedEmployeeIds, item.OrgID])]
          this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
        }
        return true
      }
      let isAllChildSelect = (flag, item, key) => {
        if (flag) {
          for (let index in item) {
            if (item[index].OrgID === key) {
              return true
            }
            if (isAllChildSelect(flag, item[index].ChildListOrgMail, key)) {
              let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
              if (SelectedEmployeeIds.indexOf(item[index].OrgID) !== -1) {
                SelectedEmployeeIds.splice(SelectedEmployeeIds.indexOf(item[index].OrgID), 1)
                this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
              }
              return true
            }
          }
        } else {
          for (let index in item) {
            for (let i in item[index].ListMail) {
              if (item[index].ListMail[i].key === key) {
                let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
                if (SelectedEmployeeIds.indexOf(item[index].OrgID) !== -1) {
                  SelectedEmployeeIds.splice(SelectedEmployeeIds.indexOf(item[index].OrgID), 1)
                  this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
                }
                return true
              }
            }
            if (isAllChildSelect(flag, item[index].ChildListOrgMail, key)) {
              let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
              if (SelectedEmployeeIds.indexOf(item[index].OrgID) !== -1) {
                SelectedEmployeeIds.splice(SelectedEmployeeIds.indexOf(item[index].OrgID), 1)
                this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
              }
              return true
            }
          }
        }
        return false
      }
      // 删除选中下面的所有孩子
      let deleteAllChild = (item) => {
        let EmployeeIds = [...new Set([...addAllChild(item)])]
        let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
        for (let i in EmployeeIds) {
          SelectedEmployeeIds.splice(SelectedEmployeeIds.indexOf(EmployeeIds[i]), 1)
        }
        this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
      }
      // 添加选中下面的所有孩子
      let addAllChild = function (item) {
        let SelectedEmployeeIds = []
        SelectedEmployeeIds.push(item.OrgID)
        for (let index in item.ChildListOrgMail) {
          SelectedEmployeeIds = [...addAllChild(item.ChildListOrgMail[index]), ...SelectedEmployeeIds]
        }
        for (let index in item.ListMail) {
          SelectedEmployeeIds.push(item.ListMail[index].key)
        }
        return SelectedEmployeeIds
      }
      childItem(item)
    },
    showChild (item) {
      if (!item.showC) {
        item['showC'] = true
      } else {
        item.showC = !item.showC
      }
      if (item.ListMail.length === 0) {
        this.$vux.loading.show({
          text: item.OrgName + '人员获取中...'
        })
        let enterpriseid = document.getElementById('EnterpriseID').value
        axios.post(this.$store.state.url + '/handler/AddressBookService.ashx', qs.stringify({enterpriseid: enterpriseid, type: 'getEmployee', orgID: item.OrgID, choosesendout: ''}))
        .then((rs) => {
          let data = rs.data
          if (data.status === 200) {
            let SelectedEmployeeIds = []
            for (let item1 of data.message) {
              item.ListMail.push({key: item1.ID, value: item1.EmployeeeName, partName: item.OrgName})
              if (this.$store.state.SelectedEmployeeIds.indexOf(item.OrgID) !== -1) {
                SelectedEmployeeIds.push(item1.ID)
              }
            }
            SelectedEmployeeIds = [...this.$store.state.SelectedEmployeeIds, ...SelectedEmployeeIds]
            this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
          } else {
            this.$vux.toast.text(data.msg, 'bottom')
          }
          this.$vux.loading.hide()
        })
        .catch((response) => {
          this.$vux.loading.hide()
          this.$vux.toast.text('请求失败请稍后再试', 'bottom')
        })
      }
      this.changeAll()
    }
  }
})
export default {
  store,
  components: {
    Group,
    Cell,
    XHeader,
    Checklist,
    XButton,
    Box,
    CheckIcon
  },
  data () {
    return {
      commonList: [],
      SelectedEmployeeIds: [],
      SelectedEmployeeNames: [],
      index: -1
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.commonList = vm.$store.state.commonList
      vm.SelectedEmployeeIds = vm.$store.state.SelectedEmployeeIds
      vm.init()
    })
  },
  mounted () {
  },
  methods: {
    deleteThis (index) {
      let findKey = (item, key) => {
        console.log(item)
        if (item.OrgID !== key) {
          for (let index in item.ChildListOrgMail) {
            findKey(item.ChildListOrgMail[index], key)
          }
        } else {
          deleteAllChild(item)
        }
      }
      // 删除选中下面的所有孩子
      let deleteAllChild = (item) => {
        let EmployeeIds = [...new Set([...addAllChild(item)])]
        let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
        console.log(EmployeeIds)
        for (let i in EmployeeIds) {
          SelectedEmployeeIds.splice(SelectedEmployeeIds.indexOf(EmployeeIds[i]), 1)
        }
        this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
      }
      // 添加选中下面的所有孩子
      let addAllChild = function (item) {
        let SelectedEmployeeIds = []
        SelectedEmployeeIds.push(item.OrgID)
        for (let index in item.ChildListOrgMail) {
          SelectedEmployeeIds = [...addAllChild(item.ChildListOrgMail[index]), ...SelectedEmployeeIds]
        }
        for (let index in item.ListMail) {
          SelectedEmployeeIds.push(item.ListMail[index].key)
        }
        return SelectedEmployeeIds
      }
      this.$store.state.SelectedShowEmployeeNames.splice(index, 1)
      findKey(this.$store.state.commonList[0], this.$store.state.SelectedShowEmployeeIds[index])
      let SelectedEmployeeIds = this.$store.state.SelectedEmployeeIds
      if (SelectedEmployeeIds.indexOf(this.$store.state.SelectedShowEmployeeIds[index]) !== -1) {
        SelectedEmployeeIds.splice(SelectedEmployeeIds.indexOf(this.$store.state.SelectedShowEmployeeIds[index]), 1)
        this.$store.commit('updateState', {key: 'SelectedEmployeeIds', value: SelectedEmployeeIds})
      }
      this.$store.state.SelectedShowEmployeeIds.splice(index, 1)
      // 找到key
    },
    init () {
      if (this.commonList.length !== 0) {
        return
      }
      this.$vux.loading.show({
        text: '数据加载中...'
      })
      let enterpriseid = document.getElementById('EnterpriseID').value || 'F9E7D8E6-32C8-43D2-8017-3BF0FAB2733B'
      axios.post(this.$store.state.url + '/handler/AddressBookService.ashx', qs.stringify({enterpriseid: enterpriseid, type: 'onlyOrg', appid: ''}))
      .then((rs) => {
        let data = rs.data
        if (data.status === 200) {
          this.commonList = data.message
          this.$store.commit('updateState', {key: 'commonList', value: this.commonList})
        } else {
          this.$vux.toast.text(data.msg, 'bottom')
        }
        this.$vux.loading.hide()
      })
      .catch((response) => {
        this.$vux.toast.text('请求失败请稍后再试', 'bottom')
        this.$vux.loading.hide()
      })
    }
  }
}
</script>

<style scoped>
  .ui-choose-list{
    background-color: white;
  }
  .ui-choose-list > div{
    position: relative;
    padding: 10px 30px 10px 10px;
    display: inline-block;
    height: 100%;
  }
</style>
